package org.rency.crawler.dal.dao.impl;

import com.mongodb.client.result.DeleteResult;
import com.mongodb.client.result.UpdateResult;
import javax.annotation.Resource;
import org.apache.commons.lang.StringUtils;
import org.rency.crawler.dal.dao.HostPoolDao;
import org.rency.crawler.dal.entity.HostPoolDO;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Repository;

/**
 * 描述: ${TODO}<br>
 * 最近修改时间:2017/12/18 14:23<br>
 *
 * @author CaiyuRen
 * @version V1.0
 * @since 2017/12/18 14:23
 */
@Repository
public class HostPoolDaoImpl implements HostPoolDao {

  @Resource
  private MongoTemplate mongoTemplate;

  @Override
  public boolean save(HostPoolDO entity) {
    try {
      mongoTemplate.save(entity);
      return true;
    } catch (DuplicateKeyException e) {
      return true;
    }
  }

  @Override
  public HostPoolDO load(String id) {
    Criteria criteria = Criteria.where("id").is(id);
    return mongoTemplate.findOne(new Query(criteria),HostPoolDO.class);
  }

  @Override
  public HostPoolDO find(String hostNo) {
    Criteria criteria = Criteria.where("hostNo").is(hostNo);
    return mongoTemplate.findOne(new Query(criteria),HostPoolDO.class);
  }

  @Override
  public long findCount() {
    return mongoTemplate.count(new Query(),HostPoolDO.class);
  }

  @Override
  public boolean updateAddress(String hostNo, String ipv4Address, String ipv6Address){
    Criteria criteria = Criteria.where("hostNo").is(hostNo);
    Update update = new Update();
    if(StringUtils.isNotEmpty(ipv4Address)){
      update.set("ipv4Address",ipv4Address);
    }
    if(StringUtils.isNotEmpty(ipv6Address)){
      update.set("ipv6Address",ipv6Address);
    }
    UpdateResult result = mongoTemplate.updateFirst(new Query(criteria),update,HostPoolDO.class);
    return result.getModifiedCount() == 1;
  }

  @Override
  public boolean delete(String hostNo) {
    Criteria criteria = Criteria.where("hostNo").is(hostNo);
    DeleteResult result = mongoTemplate.remove(new Query(criteria),HostPoolDO.class);
    return result.getDeletedCount() == 1;
  }

  @Override
  public long removeAll() {
    DeleteResult result = mongoTemplate.remove(new Query(),HostPoolDO.class);
    return result.getDeletedCount();
  }
}
